<?php

namespace app\admin\service\cms;

use tmcore\base\BaseService;
use app\common\model\article\ArticleCate;
use tmcore\exceptions\ValidateException;

/**
 * 文章栏目管理服务类
 */
class ArticleCateService extends BaseService
{

    /**
     * 获取栏目列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $searchParam = [
            '=' => ['status'],
            '%like%' => ['name']
        ];
        $where = self::getSearchData($searchParam, []);

        $lists = ArticleCate::where($where)
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->append(['status_desc', 'article_count'])
            ->select()
            ->toArray();
        return linear_to_tree($lists, 'children');
    }

    /**
     * 添加文章栏目
     * @param array $params
     * @return bool
     */
    public static function add(array $params)
    {
        return ArticleCate::add([
            'name' => $params['name'],
            'pid' => $params['pid'],
            'status' => $params['status'],
            'depth' => $params['pid']?1:2,
            'sort' => $params['sort'] ?? 0
        ]);
    }

    /**
     * 编辑文章栏目
     * @param array $params
     * @return bool
     */
    public static function edit(array $params) : bool
    {
        return ArticleCate::edit([
            'name' => $params['name'],
            'pid' => $params['pid'],
            'status' => $params['status'],
            'depth' => $params['pid']?1:2,
            'sort' => $params['sort'] ?? 0
        ], $params['id']);
    }

    /**
     * 删除文章栏目
     * @param array $params
     * @return bool
     */
    public static function delete(array $params)
    {
        return ArticleCate::del($params['id']);
    }

    /**
     * 查看文章栏目详情
     * @param $params
     * @return array
     */
    public static function detail($params) : array
    {
        return ArticleCate::findOrEmpty($params['id'])->toArray();
    }

    /**
     * 文章栏目数据
     * @return array
     */
    public static function getAllData()
    {
        $lists = ArticleCate::where(['status' => 1])
            ->field('id, pid, name')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->select()
            ->toArray();
        return linear_to_tree($lists, 'children');
    }

}